#include "head.h"

//获得前置目录id
int get_pre_dir(MYSQL *sql, const char *path, const char *uid) {
    char query[256];
    //若路径为空,则设置为默认的根路径"/"
    if (path == NULL || path[0] == '\0') {
        snprintf(query, sizeof(query), "SELECT id FROM files WHERE path = '/' AND uid = '%s'",uid);
    } else {
        snprintf(query, sizeof(query), "SELECT id FROM files WHERE path = '%s' AND uid = '%s'", path, uid);
    }

    if (mysql_query(sql, query)) {
        fprintf(stderr, "文件id查询错误: %s\n", mysql_error(sql));
        return -1;
    }

    MYSQL_RES *result = mysql_store_result(sql);
    if (!result) {
        fprintf(stderr, "结果错误: %s\n", mysql_error(sql));
        return -1;
    }
    MYSQL_ROW row = mysql_fetch_row(result);
    if (!row) {
        fprintf(stderr, "目录未找到\n");
        mysql_free_result(result);
        return -1;
    }

    int id = atoi(row[0]);
    mysql_free_result(result);
    return id;
}

//判断目录是否已经存在并且是否属于同一用户
bool path_exists(MYSQL *sql, const char *path, const char *uid) {
    char query[1024];
    snprintf(query, sizeof(query), "SELECT id FROM files WHERE path = '%s' AND uid = '%s'", path, uid);

    if (mysql_query(sql, query)) {
        fprintf(stderr, "查询路径是否存在失败: %s\n", mysql_error(sql));
        return false;
    }

    MYSQL_RES *result = mysql_store_result(sql);
    if (!result) {
        fprintf(stderr, "查询失败: %s\n", mysql_error(sql));
        return false;
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    //若有结果，表示路径存在
    bool exists = (row != NULL);
    mysql_free_result(result);
    return exists;
}


bool my_mkdir(sendMsg msg, client_status *user, int net_fd) {
    recvMsg rmsg;
    MYSQL_RES *res;
    MYSQL_ROW row;
    /*
    if(!init_sql(user->sql)){
        strcpy(rmsg.statu, "-1");
        strcpy(rmsg.msg, "数据库错误!");
        send(net_fd, &rmsg, sizeof(rmsg), 0);
        return false;
    }

    printf("数据库初始化成功\n");*/
    int base_path_size = 2000;
    char *base_path =(char *) malloc(base_path_size);
    ERROR_CHECK(base_path,NULL,"malloc");

    char last_path[2000];
    char *full_path =(char *) malloc(2000);
    ERROR_CHECK(full_path,NULL,"full_path");
    //将base_path设为当前路径
    snprintf(base_path,base_path_size,"%s",user->path);
    snprintf(last_path,sizeof(last_path),"%s",msg.msg);
    //int uid = get_user_id(user->sql,user->user_name);
    //通过token获取拆分路径
    //printf("last_path=%s\n",last_path);
    char *token = strtok(last_path,"/");

    //printf("token =%s\n",token);

    //解析多级目录并且逐级创建
    while(token!=NULL){
        int required = snprintf(NULL, 0, "%s/%s", base_path, token);
        if (required >= 2000) {
            char *new_full_path = (char *)realloc(full_path, required + 1); 
            if (!new_full_path) {
                perror("full_path分配内存失败");
                free(base_path);
                free(full_path);
                return false;
            }
            full_path = new_full_path;
        }
        //安全地更新路径
        snprintf(full_path, required + 1, "%s/%s", base_path, token);
        //printf("full_path =%s\n",full_path);

        int pre_id = get_pre_dir(user->sql,base_path,user->user_id);
        //printf("pre_id=%d\n",pre_id);

        if(!path_exists(user->sql,full_path,user->user_id)){
            char query[4096];
            //pthread_mutex_lock(&global_status.db_lock);
            snprintf(query,sizeof(query),"INSERT INTO "
                     "files (file_name, uid, pre_dir, path, file_type, create_time,finish)"
                     "VALUES ('%s', '%s', %d, '%s', 1, NOW(),1)",
                     token,user->user_id,pre_id, full_path);
            //pthread_mutex_unlock(&global_status.db_lock);
            if(mysql_query(user->sql,query)){
                fprintf(stderr,"更新数据库失败:%s\n",mysql_error(user->sql));
                strcpy(rmsg.statu, "-1");
                strcpy(rmsg.msg, "更新数据库失败！");
                send(net_fd, &rmsg, sizeof(rmsg), 0);
                return false;
            }
        }
        //更新base_path
        if (required >= base_path_size) {
            base_path_size = required + 1;
            char *new_base_path = (char *)realloc(base_path, base_path_size);
            if (!new_base_path) {
                perror("base_path 分配内存失败");
                free(base_path);
                free(full_path);
                return false;
            }
            base_path = new_base_path;
        }
        snprintf(base_path,base_path_size,"%s",full_path);
        //printf("base_path=%s\n",base_path);

        token = strtok(NULL,"/");
    }
    free(base_path);
    free(full_path);
    strcpy(rmsg.statu, "0");
    strcpy(rmsg.msg, "创建成功！");
    send(net_fd, &rmsg, sizeof(rmsg),0);
    return true;
}
